#ifndef _NO_ACE_COMPONENT
#include "ace_AsynchConnector.h"
#include "BasePacket.h"
#include "bufstream.h"
namespace XGC
{
	namespace net
	{

		volatile long ace_AsynchConnector::_ref = 0;
		ace_AsynchConnector::ace_AsynchConnector( create_handler_func pFunc, long_ptr lParam )
			: m_pFunc( pFunc )
			, m_lParam( lParam )
		{
			InterlockedIncrement( &_ref );
		}

		ace_AsynchConnector::~ace_AsynchConnector(void)
		{
			this->cancel();
			InterlockedDecrement( &_ref );
		}

		void ace_AsynchConnector::handle_connect(const ACE_Asynch_Connect::Result &result)
		{
			int ret = -1;
			if ( result.error() != 0 )
			{
				IMessageQueue* pMessageQueue = (IMessageQueue*)result.act();
				if( pMessageQueue )
				try
				{
					CNetworkPacket* pPacket = new CNetworkPacket( 2, NULL, -1 );
					bufstream in( pPacket->data(), pPacket->size() );
					in
						<< _byte(SYSTEM_MESSAGE_TYPE)
						<< _byte(EVENT_ERROR)
						;

					pMessageQueue->PushMessage( pPacket );
				}
				catch( CNetworkPacket* pPacket )
				{
					pPacket->release();
				}
			}

			__super::handle_connect(result);
			delete this;
		}

		int ace_AsynchConnector::validate_connection (const ACE_Asynch_Connect::Result& result,
										 const ACE_INET_Addr &remote,
										 const ACE_INET_Addr& local)
		{
			if( result.error() != 0 )
				return -1;

			//ACE_SOCK_SEQPACK_Association ass(handle());
			//ass.get_remote_addr(m_RemoteAddress);
			int opt = 1;
			// Set Keepalive option;
			if( setsockopt((SOCKET)result.connect_handle(), SOL_SOCKET, SO_KEEPALIVE, (char*)&opt, sizeof(opt)) != SOCKET_ERROR )
			{
				/* Argument structure for SIO_KEEPALIVE_VALS */
				struct tcp_keepalive 
				{
					u_long  onoff;
					u_long  keepalivetime;
					u_long  keepaliveinterval;
				};

				tcp_keepalive inkeepalive = { 1, 5000, 5000 };
				tcp_keepalive outkeepalive;
				DWORD dwRet = 0;
				WSAIoctl( (SOCKET)result.connect_handle(), (IOC_IN|IOC_VENDOR|4), (LPVOID)&inkeepalive, sizeof(inkeepalive), (LPVOID)&outkeepalive, sizeof(outkeepalive), &dwRet, NULL, NULL );
			}

			return 0;
		}
	}
}
#endif